
#include "member_BAnimation.h"
#include "member_BChannel.h"
#include "member_BNode.h"
#include "member_BWidget.h"

using namespace BWE;

member_BAnimation::member_BAnimation(BAnimation* animation)
{
	boss = animation;
	hostNode = 0;
	hostWidget = 0;
	loop = true;
	duration = 0;
	pause = true;
	time = 0;
	timeStart = 0;
	timePause = 0;
}
member_BAnimation::~member_BAnimation()
{

}

void member_BAnimation::attach(BObject* object)
{
	hostNode = dynamic_cast<BNode*>(object);
	hostWidget = dynamic_cast<BWidget*>(object);
	linkChannels();
}
void member_BAnimation::detach()
{
	if (hostNode)
		hostNode->removeAnimation(boss);
	hostWidget = 0;
	unlinkChannels();
}

void member_BAnimation::linkChannel(BChannel* channel)
{
	BObject* object = findObject(channel_member(channel)->targetName);
	if (object && channel->accept(object))
	{
		channel_member(channel)->target = object;
	}
}
void member_BAnimation::linkChannels()
{
	for (int i = 0; i < channels.size(); i++)
	{
		BChannel* channel = channels[i];
		if (channel_member(channel)->targetName.empty())
			continue;
		linkChannel(channel);
	}
}
void member_BAnimation::unlinkChannels()
{
	for (int i = 0; i < channels.size(); i++)
	{
		BChannel* channel = channels[i];
		channel_member(channel)->target = 0;
	}
}

BObject* FindObject(BNode* node, const BString& name)
{
	if (!node)
		return 0;
	if (node->name() == name)
		return node;
	for (int i = 0; i < node_member(node)->shapeItems.size(); i++)
	{
		BShape* shape = node_member(node)->shapeItems[i].shape;
		if (shape->name() == name)
			return shape;
	}
	return 0;
}
BObject* FindObject(BWidget* widget, const BString& name)
{
	if (!widget)
		return 0;
	if (widget->name() == name)
		return widget;
	for (BWidget* child : widget_member(widget)->children)
	{
		BObject* object = FindObject(child, name);
		if (object)
			return object;
	}
	return 0;
}

BObject* member_BAnimation::findObject(const BString& name)
{
	if (hostNode)
		return FindObject(hostNode, name);
	if (hostWidget)
		return FindObject(hostWidget, name);
	return 0;
}
